import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { Form, Input, Button, Card, message } from "antd";
import { HeartFilled, KeyOutlined, MobileFilled } from "@ant-design/icons";

import { login, LoginParams, register, RegisterParams } from "../../services/auth";

import styles from "./Login.module.scss";

const Login = () => {
  const [loading, setLoading] = useState(false);
  const [isLogin, setIsLogin] = useState(true);
  const navigate = useNavigate();
  const [messageApi, contextHolder] = message.useMessage();

  const handleLogin = async (values: LoginParams) => {
    setLoading(true);
    try {
      const response = await login(values);
      if (response.token) {
        localStorage.setItem("token", response.token);
        messageApi.success("登录成功，正在跳转...");
        navigate("/agents");
      }
      else {
        messageApi.error("登录失败，请检查手机号和密码是否正确");
      }
    } catch (error: any) {
      const errorMsg = error.response?.data?.message;
      if (errorMsg) {
        messageApi.error(`登录失败：${errorMsg}`);
      } else {
        messageApi.error("登录失败，服务器连接异常，请稍后重试");
      }
    } finally {
      setLoading(false);
    }
  };

  const handleRegister = async (values: RegisterParams) => {
    setLoading(true);
    try {
      const response = await register(values);
      if (response?.error) {
        messageApi.error(`注册失败：${response?.message}`);
      }
      else {
        messageApi.success("注册成功！您现在可以登录了");
        setIsLogin(true);
      }
    } catch (error: any) {
      const errorMsg = error.response?.data?.message;
      if (errorMsg) {
        messageApi.error(`注册失败：${errorMsg}`);
      } else {
        messageApi.error("注册失败，服务器连接异常，请稍后重试");
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={styles.loginContainer}>
      {contextHolder}
      <div className={styles.loginBox}>
        <Card className={styles.card}>

          <h1 className={styles.title}>九紫商学AI平台</h1>

          <p className={styles.description}>AI改变人生，助力全国创业女性</p>

          {isLogin ? (
            <>
              <Form
                name="login"
                initialValues={{ remember: true }}
                onFinish={handleLogin}
                size="large"
                className={styles.form}
              >
                <Form.Item
                  name="username"
                  rules={[
                    { required: true, message: "请输入手机号" },
                    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号" },
                  ]}
                >
                  <Input prefix={<MobileFilled style={{ color: '#a680b9' }} />} placeholder="请输入手机号" />
                </Form.Item>
                <Form.Item
                  name="password"
                  rules={[
                    { required: true, message: "请输入密码" },
                  ]}
                >
                  <Input.Password prefix={<KeyOutlined style={{ color: '#a680b9' }} />} placeholder="请输入密码" />
                </Form.Item>
                <Form.Item>
                  <Button
                    type="primary"
                    htmlType="submit"
                    className={styles.loginButton}
                    loading={loading}
                    block
                  >
                    登录
                  </Button>
                </Form.Item>
                <div className={styles.registerHint}>
                  还没有账号？{" "}
                  <Button className={styles.goRegisterButton} type="link" onClick={() => setIsLogin(false)}>
                    立即注册
                  </Button>
                </div>
              </Form>
            </>
          ) : (
            <Form
              name="register"
              initialValues={{ remember: false }}
              onFinish={handleRegister}
              size="large"
              className={styles.form}
            >
              <Form.Item
                name="username"
                rules={[
                  { required: true, message: "请输入手机号" },
                  { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号" },
                ]}
              >
                <Input prefix={<MobileFilled style={{ color: '#a680b9' }} />} placeholder="请输入手机号" />
              </Form.Item>
              <Form.Item
                name="password"
                rules={[
                  { required: true, message: "请输入密码" },
                  { min: 6, message: "密码长度不能少于6位" },
                  {
                    pattern: /^(?![0-9]+$)[a-zA-Z0-9_!@#$%^&*(),.?":{}|<>]{6,}$/,
                    message: "密码不能为纯数字，需包含字母或特殊符号"
                  }
                ]}
              >
                <Input.Password prefix={<KeyOutlined style={{ color: '#a680b9' }} />} placeholder="密码（至少6位，不能是纯数字）" />
              </Form.Item>
              <Form.Item
                name="passwordConfirm"
                dependencies={['password']}
                rules={[
                  { required: true, message: "请确认密码" },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue('password') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('两次输入的密码不一致'));
                    },
                  }),
                ]}
              >
                <Input.Password prefix={<KeyOutlined style={{ color: '#a680b9' }} />} placeholder="请再次输入密码" />
              </Form.Item>
              <Form.Item
                name="inviteCode"
                rules={[
                  { required: true, message: "邀请码为必填项，请输入邀请码" },
                  { whitespace: true, message: "邀请码不能为空" }
                ]}
              >
                <Input
                  prefix={<HeartFilled style={{ color: '#a680b9' }} />}
                  placeholder="请输入邀请码（必填）"
                />
              </Form.Item>

              <Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  className={styles.loginButton}
                  loading={loading}
                  block
                >
                  注册
                </Button>
              </Form.Item>
              <div className={styles.registerHint}>
                已有账号？{" "}
                <Button type="link" onClick={() => setIsLogin(true)}>
                  立即登录
                </Button>
              </div>
            </Form>
          )}
        </Card>
      </div>
    </div>
  );
};

export default Login;
